const router = require('koa-router')()
const formidable = require('formidable');
const fs = require('fs');
const path = require('path')

let list = [
  {
    chapterId:'1',
    chapterTitle:'中国议民生，美国忙党争，两国开会大不同',
    time:'2023-3-3'
  },
  {
    chapterId:'2',
    chapterTitle:'全面推进城乡、区域协调发展',
    time:'2023-1-12'
  },
  {
    chapterId:'3',
    chapterTitle:'网友在生态园拍到现实版“乌鸦喝水” 工作人员回应',
    time:'2022-11-18'
  }
]

router.get('/my', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

//开发场景的前后端交互过程
//前端 vue、react脚手架 小程序
//后端 koa2
//前后端交互 vue、react使用axios 小程序使用wx.request
//跨域问题，浏览器存在同源策略
//同源指的是 协议、域名以及IP地址、端口保持一致
//不同源时会发生跨域问题
//解决跨域问题：①代理服务器②后端允许跨域（koa2-cors）

router.get('/getdata', async (ctx, next) => {
  /**
   * 给响应资源添加响应头Expires
   * 设置格林尼治格式的时间
   * 浏览器拿到该时间之后，在该时间前会使用之前缓存的数据
   * 超过该时间后，仍会向服务器请求
   * 
   * 强缓存（强制缓存）
  */
  let timer = new Date(Date.now() + 30000)
  timer = timer.toGMTString()

  ctx.set('Expires',timer)
  //ctx.body = 'HTTP强缓存之Expires'

  ctx.body = [
    {"name":"lisi","age":"19"},
    {"name":"zhangsan","age":"24"},
    {"name":"wangwu","age":"32"},
  ] ;
})

router.get('/getcache', (ctx, next) => {
  ctx.set('Cache-Control','public, max-age=30')

  /**
   * 强制缓存
   * 设置过期时间，Cache-Control值为
   * public，max-age=秒
   * 超时后会继续从服务端获取
  */

  ctx.body = [
    {"name":"lisi","age":"19"},
    {"name":"zhangsan","age":"24"},
    {"name":"wangwu","age":"32"},
  ] ;
})

router.get('/getList', async (ctx, next) => {
  ctx.body = list;
})

router.post('/sub', async (ctx, next) => {
  let chapterTitle = ctx.request.body.chapterTitle;
  let chapterObj = {
    chapterId:list.length,
    chapterTitle:chapterTitle,
    time:'2023-3-3'
  }

  list.push(chapterObj);

  ctx.body = 'ok'
})

router.post('/delete', async (ctx, next) => {
  let id = ctx.request.body.chapterId;
  for(let i=0;i <list.length;i++) {
    if(list[i].chapterId === id) {
      list.splice(i,1);
      ctx.body = {'code':200,'msg':'ok'};
      break;
    }
  }
})

router.post('/subForm', async (ctx, next) => {
  let chapterTitle = ctx.request.body.chapterTitle;
  let time = ctx.request.body.time;
  let dateObj = new Date(time);
  time = dateObj.getFullYear()+'-'+(dateObj.getMonth()+1)+'-'+(dateObj.getDate());

  let chapterObj = {
    chapterId:Math.random(),
    chapterTitle:chapterTitle,
    time:time
  }

  list.unshift(chapterObj)

  ctx.body = {'code':200,msg:'success'}
})

router.post('/subEditForm', async(ctx, next) => {
  let chapterId = ctx.request.body.chapterId;
  let chapterTitle = ctx.request.body.chapterTitle;
  let time = ctx.request.body.time;

  for(let i=0;i<list.length;i++) {
    if(chapterId == list[i].chapterId) {
      list[i].chapterTitle = chapterTitle;
      list[i].time = time;
      ctx.body = {'code':200,'msg':'ok'}
      break;
    }
  }
})

router.post('/upload', async(ctx, next) => {
  const form = formidable({multiples:true,uploadDir:'public/images',keepExtensions:true});

  form.parse(ctx.req, async(err, fields, files) => {
    if(err) {
      ctx.body = {'code':500,'msg':err}
    }
    ctx.body = {'code':200,'msg':'成功'}
  })
})

router.get('/userlist', async(ctx, next) => {
  ctx.body = [
    {'username':'zhangsan','age':18},
    {'username':'lisi','age':20}
  ]
})

router.get('/getImage', async(ctx, next) => {
  let imgUrl = path.join(__dirname,'../public/logo.png')

  let image = fs.readFileSync(imgUrl)

  ctx.type = 'image/png'

  ctx.body = image;
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
